{% extends 'base/base.html' %}
{% load static %}

{% block title %}我的订单 - 妙趣拾光锦盒{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="/static/css/payment.css">
<style>
    .order-action-buttons .btn {
        margin-right: 5px;
        margin-bottom: 5px;
    }

    @media (max-width: 768px) {
        .order-action-buttons {
            display: flex;
            flex-direction: column;
            align-items: flex-start;
        }
        
        .order-action-buttons .btn {
            margin-top: 5px;
            width: 100%;
        }
    }
    
    /* 支付方式样式 */
    .payment-method {
        padding: 12px !important;
        margin: 0 10px;
        border-radius: 6px;
        cursor: pointer;
        width: 100px;
        text-align: center;
        transition: all 0.2s ease;
    }
    
    .payment-method.wechat {
        border: 2px solid transparent;
        background-color: #f8f8f8;
    }
    
    .payment-method.alipay {
        border: 2px solid transparent;
        background-color: #f8f8f8;
    }
    
    .payment-method.wechat.active {
        border-color: #07c160;
        background-color: #f0fff4;
    }
    
    .payment-method.alipay.active {
        border-color: #1677ff;
        background-color: #f0f9ff;
    }
    
    .payment-method .method-name {
        font-size: 16px;
        font-weight: 500;
    }
    
    .payment-method.wechat .method-name {
        color: #07c160;
    }
    
    .payment-method.alipay .method-name {
        color: #1677ff;
    }
    
    .payment-close {
        cursor: pointer;
        font-size: 22px;
        font-weight: 300;
        color: #888;
        transition: color 0.2s ease;
    }
    
    .payment-close:hover {
        color: #333;
    }
</style>
{% endblock %}

{% block content %}
<section class="py-5">
    <div class="container">
        <h1 class="mb-4">我的订单</h1>
        
        <div class="row">
            <div class="col-12">
                {% if orders %}
                <div class="card shadow-sm">
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-hover mb-0">
                                <thead class="table-light">
                                    <tr>
                                        <th class="ps-3">订单号</th>
                                        <th>下单时间</th>
                                        <th>总金额</th>
                                        <th>状态</th>
                                        <th class="pe-3">操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for order in orders %}
                                    <tr>
                                        <td class="ps-3">{{ order.order_no }}</td>
                                        <td>{{ order.create_time|date:"Y-m-d H:i" }}</td>
                                        <td>¥{{ order.total_amount }}</td>
                                        <td>
                                            {% if order.status == 1 %}
                                            <span class="badge bg-warning">待支付</span>
                                            {% elif order.status == 2 %}
                                            <span class="badge bg-info">待发货</span>
                                            {% elif order.status == 3 %}
                                            <span class="badge bg-primary">已发货</span>
                                            {% elif order.status == 4 %}
                                            <span class="badge bg-success">已完成</span>
                                            {% elif order.status == 5 %}
                                            <span class="badge bg-danger">已取消</span>
                                            {% endif %}
                                        </td>
                                        <td class="pe-3 order-action-buttons">
                                            <a href="{% url 'order:detail' order.order_id %}" class="btn btn-sm btn-outline-primary">
                                                <i class="fas fa-eye me-1"></i>查看详情
                                            </a>
                                            {% if order.status == 1 %}
                                            <button type="button" class="btn btn-sm btn-primary pay-order-btn" data-order-id="{{ order.order_id }}" data-order-amount="{{ order.total_amount }}">
                                                <i class="fas fa-credit-card me-1"></i>去支付
                                            </button>
                                            {% endif %}
                                        </td>
                                    </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                {% else %}
                <div class="card shadow-sm">
                    <div class="card-body p-4 text-center">
                        <div class="mb-4">
                            <i class="fas fa-shopping-bag fa-4x text-muted"></i>
                        </div>
                        <h4 class="mb-3">您还没有订单</h4>
                        <p class="text-muted mb-4">去选购您喜欢的盲盒吧</p>
                        <a href="{% url 'blindbox:list' %}" class="btn btn-primary">
                            <i class="fas fa-shopping-bag me-2"></i>浏览商品
                        </a>
                    </div>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
</section>
{% endblock %}

{% block extra_js %}
<script src="/static/js/payment.js"></script>
<script>
    $(document).ready(function() {
        // 支付按钮点击事件
        $('.pay-order-btn').click(function() {
            const orderId = $(this).data('order-id');
            const orderAmount = $(this).data('order-amount');
            showPaymentModal(orderId, orderAmount);
        });
        
        // 显示支付弹窗
        function showPaymentModal(orderId, orderAmount) {
            // 检查是否已经有支付弹窗，如果有则先移除
            const oldModal = document.getElementById('paymentModal');
            if (oldModal) {
                oldModal.remove();
            }

            // 创建支付弹窗
            const modal = document.createElement('div');
            modal.id = 'paymentModal';
            modal.className = 'payment-modal';
            
            // 默认选择微信支付
            let selectedMethod = 'wechat';
            
            // 选择最接近的金额的二维码
            const availableAmounts = [10, 50, 100];
            let closestAmount = availableAmounts.reduce((prev, curr) => {
                return (Math.abs(curr - orderAmount) < Math.abs(prev - orderAmount) ? curr : prev);
            });
            
            // 创建弹窗内容
            modal.innerHTML = `
                <div class="payment-content">
                    <div class="payment-header">
                        <h3>付款</h3>
                        <span class="payment-close">×</span>
                    </div>
                    <div class="payment-body">
                        <div class="payment-amount">
                            <div class="payment-price-title">扫一扫付款（元）</div>
                            <div class="payment-price">${orderAmount}</div>
                        </div>
                        <div class="payment-methods">
                            <div class="payment-method wechat active" data-method="wechat">
                                <div class="method-name">微信支付</div>
                            </div>
                            <div class="payment-method alipay" data-method="alipay">
                                <div class="method-name">支付宝</div>
                            </div>
                        </div>
                        <div class="payment-qrcode">
                            <div class="qrcode-container">
                                <img src="" alt="支付二维码" id="payment-qrcode-img">
                            </div>
                            <div class="qrcode-tip">请使用微信扫一扫<br>扫描二维码支付</div>
                        </div>
                        <div class="payment-timer">
                            <span>二维码有效期 15 分钟</span>
                            <span class="payment-timer-text">请尽快完成支付</span>
                        </div>
                        <div class="mt-3 text-center">
                            <button type="button" class="btn btn-outline-secondary cancel-payment-btn">
                                取消支付
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            // 添加到页面
            document.body.appendChild(modal);
            
            // 显示弹窗
            setTimeout(() => {
                modal.classList.add('show');
            }, 10);
            
            // 生成随机支付码并获取二维码
            const generatePaymentCode = () => {
                // 生成随机字母数字字符串作为支付码
                const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
                let paymentCode = '';
                for (let i = 0; i < 16; i++) {
                    paymentCode += characters.charAt(Math.floor(Math.random() * characters.length));
                }
                
                // 构建二维码数据
                const qrcodeData = {
                    method: selectedMethod,
                    amount: orderAmount,
                    code: paymentCode,
                    time: new Date().getTime()
                };
                
                // 获取二维码图片
                $.ajax({
                    url: "/orders/generate_qrcode/",
                    type: "GET",
                    dataType: "json",
                    data: {
                        method: selectedMethod,
                        amount: orderAmount,
                        code: paymentCode,
                        json: true
                    },
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    success: function(response) {
                        // 直接显示二维码，不需要处理加载动画
                        const qrcodeImg = document.getElementById('payment-qrcode-img');
                        qrcodeImg.src = response.image_data;
                        
                        console.log("二维码加载成功", response.payment_code);
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        // 显示错误信息
                        console.error("二维码加载失败", textStatus, errorThrown);
                        document.getElementById('qrcode-loading').innerHTML = '<div class="text-danger">二维码加载失败，请重试</div>';
                        document.getElementById('qrcode-loading').style.display = 'flex';
                    }
                });
            };
            
            // 立即生成二维码
            generatePaymentCode();
            
            // 绑定关闭按钮事件
            modal.querySelector('.payment-close').addEventListener('click', () => {
                closePaymentModal();
            });
            
            // 绑定取消支付按钮事件
            modal.querySelector('.cancel-payment-btn').addEventListener('click', () => {
                closePaymentModal();
            });
            
            // 添加支付方式切换功能
            const methodElements = modal.querySelectorAll('.payment-method');
            methodElements.forEach(el => {
                el.addEventListener('click', function() {
                    const method = this.getAttribute('data-method');
                    
                    // 移除其他选中状态
                    methodElements.forEach(item => item.classList.remove('active'));
                    
                    // 添加当前选中状态
                    this.classList.add('active');
                    
                    // 更新选中的支付方式
                    selectedMethod = method;
                    
                    // 更新提示文字
                    const tipText = method === 'wechat' ? '请使用微信扫一扫<br>扫描二维码支付' : '请使用支付宝扫一扫<br>扫描二维码支付';
                    modal.querySelector('.qrcode-tip').innerHTML = tipText;
                    
                    // 重新生成二维码
                    generatePaymentCode();
                });
            });
            
            // 模拟支付过程（10秒后显示支付成功）
            const paymentTimer = setTimeout(() => {
                closePaymentModal();
                
                // 使用AJAX方式更新订单状态
                $.ajax({
                    url: `/orders/${orderId}/pay-ajax/`,
                    type: "POST",
                    dataType: "json",
                    success: function(response) {
                        showPaymentSuccess();
                        
                        // 2秒后自动关闭支付成功提示并刷新页面
                        setTimeout(() => {
                            closePaymentSuccess();
                            // 刷新页面显示最新状态
                            location.reload();
                        }, 2000);
                    },
                    error: function(xhr, status, error) {
                        let errorMsg = "支付处理失败，请稍后再试";
                        if (xhr.responseJSON && xhr.responseJSON.message) {
                            errorMsg = xhr.responseJSON.message;
                        }
                        alert(errorMsg);
                    }
                });
            }, 10000);
            
            // 如果用户手动关闭，需要清除定时器
            modal.querySelector('.payment-close').addEventListener('click', () => {
                clearTimeout(paymentTimer);
            });
            
            modal.querySelector('.cancel-payment-btn').addEventListener('click', () => {
                clearTimeout(paymentTimer);
            });
        }
        
        // 关闭支付弹窗
        function closePaymentModal() {
            const modal = document.getElementById('paymentModal');
            if (!modal) return;
            
            modal.classList.remove('show');
            setTimeout(() => {
                modal.remove();
            }, 300);
        }
        
        // 显示支付成功提示
        function showPaymentSuccess() {
            // 创建支付成功提示
            const successModal = document.createElement('div');
            successModal.id = 'paymentSuccessModal';
            successModal.className = 'payment-success-modal';
            
            successModal.innerHTML = `
                <div class="payment-success-content">
                    <div class="payment-success-icon">
                        <i class="fas fa-check-circle"></i>
                    </div>
                    <h3>支付成功</h3>
                    <p>订单已支付，感谢您的购买！</p>
                </div>
            `;
            
            // 添加到页面
            document.body.appendChild(successModal);
            
            // 显示弹窗
            setTimeout(() => {
                successModal.classList.add('show');
            }, 10);
        }
        
        // 关闭支付成功提示
        function closePaymentSuccess() {
            const modal = document.getElementById('paymentSuccessModal');
            if (!modal) return;
            
            modal.classList.remove('show');
            setTimeout(() => {
                modal.remove();
            }, 300);
        }
    });
</script>
{% endblock %} 